<?php
/**
 * 搜窝
 *
 * @copyright 搜窝( www.souvo.com )
 * @package 前台用户登录
 * @version 1.0
 * @author wybwsk(wybwsk@thinkbuy.net)
 * @date 2011/5/2
 */
class FrontAction extends Action {
    /**
     * 当前用户信息
     *
     * @access protected
     */
    protected $user = FALSE;
    protected $user_info = FALSE;

    /**
     * current navigation
     */
    protected $console_top_nav = array();
    protected $console_sub_nav = array();
    protected $index_top_nav = array();

    /**
     * 当前用户的ip地址
     */
    protected $ip = '';

    protected $ajax = false;
    protected $post = false;

    protected $timestamp = 0;

    protected $root_path = '';

    protected $root_rel_path = '';

    protected $cate_cache_path = '';
    /**
     * 系统初始化方法
     *
     * @access protected
     */
    protected function _initialize() {
        ob_start(array($this,'ob_callback'));
        header('Content-type:text/html; charset=utf-8');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Cache-Control: private');
        Load('extend');

        $this->root_path = dirname($_SERVER['PHP_SELF']);
        $this->root_rel_path = realpath(dirname($_SERVER['SCRIPT_FILENAME']));
        $this->cate_cache_path = DATA_PATH.'cate/';
        $this->ajax = $this->isAjax();
        $this->post = strtolower($_SERVER['REQUEST_METHOD']) == 'post';

        $top_category_navigation = array();

        $this->ip = get_client_ip();

        $this->assign('pro_city',W('proCity',array(),true));

        $this->timestamp = time();

        // 当前用户处于哪个栏目
        if(GROUP_NAME === 'Console') {
            $this->console_top_nav[strtolower(MODULE_NAME)] = ' current';
            $this->console_sub_nav[strtolower(MODULE_NAME).'_'.strtolower(ACTION_NAME)] = ' current';
            if(ACTION_NAME === 'cateadd' || ACTION_NAME === 'cateedit') {
                $this->console_sub_nav[strtolower(MODULE_NAME).'_cate'] = ' current';
            }
            $menu = W('consoleMenu',array(),true);
            $this->assign('menu',$menu);
            $module_name = strtolower(MODULE_NAME);
            $this->assign('title',$menu[$module_name]['title']);
            $this->assign('currTopNav',$this->console_top_nav);
            $this->assign('currSubNav',$this->console_sub_nav);
        }else{
            $act_name = strtolower(MODULE_NAME).'_'.strtolower(ACTION_NAME);
        }

        // 如果当前用户验证身份cookie有效则获取相用户信息
        if ( isset($_SESSION['auth']) && $this->validAuthCookie() ) {
            C('formtoken_extra',$this->user['mid'].$this->user['password']);

        }
        if(method_exists($this,'init')){
            $this->init();
        }
     }

     /**
      * 页面压缩输出
      */
     public function ob_callback($buffer) {
         header('Etag: '.md5($buffer));
         if( extension_loaded('zlib') AND strstr($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') ) {
             $buffer = gzencode($buffer,9);

             header('Content-Encoding: gzip');
             header('Vary: Accept-Encoding');
             header('Content-Length: '.strlen($buffer));
         }
         return $buffer;
     }

    protected function validToken() {
        // 如果开启了Token验证
        if( C('TOKEN_ON') ) {
            $token = formtoken();
            return $_REQUEST[C('TOKEN_NAME')] != $token ? FALSE : TRUE;
        }
        return true;
    }

    /**
     * 验证网站来路
     * @param bool $coerce 是否强制验证默认为false
     */
    protected function validReferer($coerce = false) {
        $referer = $_SERVER['HTTP_REFERER'];
        if( empty($referer) && !$coerce ){
            return true;
        }
        $referer = parse_url($referer);
        return $referer['host'] == $_SERVER['HTTP_HOST'];
    }

    /**
     * 验证来路及表单
     *
     * @param bool $coerce 是否强制验证来路
     */
    protected function validTR($coerce = false) {
        return $this->validToken() AND $this->validReferer($coerce);
    }

    protected function setAuthCookie($expire=0,$type="s") {
		$auth = @serialize($this->user);
		$encrypt_result = $this->authcode($auth,'ENCODE',C('auth_key').$_SERVER['HTTP_USER_AGENT']);
		$encrypt_result = str_replace('+','JIAHAO',base64_encode($encrypt_result));
        $type=="c" ? cookie('auth',$encrypt_result,$expire) : $_SESSION['auth']=$encrypt_result;
    }

    protected function disAuthCookie($type="s") {
        ($type=="c") ? cookie('auth',NULL) : $_SESSION['auth']=NULL;
    }

    protected function validAuthCookie($type="s") {
		$auth = ($type=="c") ? urldecode(cookie('auth')) : urldecode($_SESSION['auth']);
        $decrypt_result = $this->authcode(base64_decode(str_replace('JIAHAO','+',$auth)),'DECODE',C('auth_key').$_SERVER['HTTP_USER_AGENT']);
		if($decrypt_result){
			$this->user = @unserialize($decrypt_result);
            if($this->user) {
                $this->user_info = M('member_info')->where(array('mid'=>$this->user['mid']))->find();
            }
    		return true;
		}
		return false;
    }

    /**
     * 空操作方法
     *
     * @access public
     */
    public function _empty() {
         $str = '<h1>页面不存在</h1><h2>Module:'.MODULE_NAME.'<br />Action:'.ACTION_NAME.'</h2><h3><a href="'.U('main/index').'">回首页</a>&nbsp;<a href="javascript:history.back(-1);">返回上一页面</a></h3>';
         echo $str;
    }

    /**
     * 获取当前的URL地址
     */
    protected function getCurrentUrl() {
        return 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    }

    /**
     * 获取带表前缀的表名
     */
    protected function table($table_name) {
        return '`'.C('db_prefix').$table_name.'`';
    }

    /**
     * 生成 script 标签
     */
    protected function loadScript($filename,$type="1") {
        $scripts = explode(',',$filename);
        $script = '';
        if($type=="1") {
            foreach ($scripts as $filename) {
                $script .= '<script src="'.__APP__.'/resources/js/'.$filename.'.js?r='.rand().'" type="text/javascript" charset="utf-8"></script>'."\n";
            }
        }else{
            foreach ($scripts as $filename) {
                $script .='<link rel="stylesheet" href="'.__APP__.'/resources/css/'.$filename.'.css" type="text/css" charset="utf-8">'."\n";
            }
        }
        return $script;
    }

    /**
     * 输出JSON数据
     */
    protected function outJsonMsg($err,$msg) {
        $std = new stdClass();
        $std->err = $state;
        $std->msg = $msg;
        return json_encode($std);
    }

	/**
	 * authcode 加密解密
	 */
	protected function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {

		$ckey_length = 4;
		$key = md5($key ? $key : C('auth_key'));
		$keya = md5(substr($key, 0, 16));
		$keyb = md5(substr($key, 16, 16));
		$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

		$cryptkey = $keya.md5($keya.$keyc);
		$key_length = strlen($cryptkey);

		$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
		$string_length = strlen($string);

		$result = '';
		$box = range(0, 255);

		$rndkey = array();
		for($i = 0; $i <= 255; $i++) {
			$rndkey[$i] = ord($cryptkey[$i % $key_length]);
		}

		for($j = $i = 0; $i < 256; $i++) {
			$j = ($j + $box[$i] + $rndkey[$i]) % 256;
			$tmp = $box[$i];
			$box[$i] = $box[$j];
			$box[$j] = $tmp;
		}

		for($a = $j = $i = 0; $i < $string_length; $i++) {
			$a = ($a + 1) % 256;
			$j = ($j + $box[$a]) % 256;
			$tmp = $box[$a];
			$box[$a] = $box[$j];
			$box[$j] = $tmp;
			$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
		}

		if($operation == 'DECODE') {
			if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
				return substr($result, 26);
			} else {
				return '';
			}
		} else {
			return $keyc.str_replace('=', '', base64_encode($result));
		}

	}

    protected function getPageData($model,$listRows,$parameter,$order,$table) {
        if(!class_exists('Page')) {
            import('ORG.Util.Page');
        }
        $model = is_object($model) ? $model : M($model);

        $count = (int) $model->table($table)->where($parameter)->order($order)->count();

        $page = new Page($count,$listRows);
        $page->parameter = http_build_query($parameter);
        $return = array(
                'page_list' => $page->show(),
                'data_list' => (array)$model->table($table)->where($parameter)->order($order)->limit($page->firstRow.','.$page->listRows)->findAll(),
            );
        return $return;
    }

    protected function checkConsoleLogin() {
        return ($this->user && $this->user['rule'] === md5(sha1(C('auth_key')))) ? TRUE : FALSE;
    }
}